package com.dayouzi.crawler_monitor.config;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Objects;

@Aspect
@Component
@Order(-1) // 设置优先级最高，高于@Transactional
public class DataSourceAspect {

//    @Pointcut("execution(* com.dayouzi.crawler_monitor..*.*(..))")
    @Pointcut("@annotation(DataSource) || @within(DataSource)")
    private void pointCut() {
    }

    @Before("pointCut()")
    public void before(JoinPoint joinPoint) {
        Class<?> clazz = joinPoint.getTarget().getClass();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        // 先查看方法上是否有注解
        DataSource annotation = method.getDeclaredAnnotation(DataSource.class);
        // 如果方法上没有注解，则查看类上是否有注解
        if (Objects.isNull(annotation)) {
            annotation = clazz.getAnnotation(DataSource.class);
        }
        if (Objects.nonNull(annotation)) {
            DataSourceContextHolder.setDataSourceType(annotation.value());
        } else {
            DataSourceContextHolder.setDataSourceType("onlyforcrawlerweb");
        }
    }

    @After("pointCut()")
    public void after(JoinPoint joinPoint) {
        DataSourceContextHolder.clearDataSourceType();
    }
}